package com.syxbbs.forum.controller;

import com.syxbbs.forum.common.AppResult;
import com.syxbbs.forum.common.ResultCode;
import com.syxbbs.forum.config.AppConfig;
import com.syxbbs.forum.exception.ApplicationException;
import com.syxbbs.forum.model.Article;
import com.syxbbs.forum.model.ArticleReply;
import com.syxbbs.forum.model.User;
import com.syxbbs.forum.services.Impl.ArticleServiceImpl;
import com.syxbbs.forum.services.Impl.IArticleReplyImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("reply")
@Slf4j
public class ArticleReplyController {

    @Resource
    IArticleReplyImpl iArticleReply;

    @Resource
    ArticleServiceImpl articleService;

    @RequestMapping("/create")
    public AppResult create(@RequestParam("articleId") Long articleId, HttpServletRequest request,@RequestParam("content") String content){
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState()==1){
            //被禁言了
            return AppResult.failure(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(articleId);
        if (article==null || article.getDeleteState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());


        }
        if (article.getState()==1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_BANNED.toString());

        }
        ArticleReply articleReply=new ArticleReply();
        articleReply.setContent(content);
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        iArticleReply.create(articleReply);
        return AppResult.success();

    }

    @RequestMapping("/getReplies")
    public AppResult getRepliesByArticleId(@NonNull Long articleId){
        Article article = articleService.selectById(articleId);
        if (article==null){
            return AppResult.failure(ResultCode.FAILED_NOT_EXISTS);
        }
        List<ArticleReply> articleReplies = iArticleReply.selectByArticleId(articleId);
        return AppResult.success(articleReplies);


    }



}
